// 登录
import {defineStore} from 'pinia'
import { Profile } from  '@/types/user'
import  request  from '@/utils/request'
import { IResponse } from '@/types/data'
import {setProfile,getProfile,removeProfile} from '@/utils/storage'
import useStore from '@/store'

export default defineStore({
  id:'user',
  state:() => ({
    profile: getProfile()
  }),
  actions: {
    // 用户名密码登录
    async login(account:string,password:string) {
      const res = await request.post<IResponse<Profile>>('/login',{
        account,
        password
      })
      this.profile = res.data.result
      // 信息持久化
      setProfile(res.data.result)
      console.log('登录成功',res)
    },
    // 获取手机验证码
    async sendMobileMsg(mobile: string) {
     const res = await request.get('/login/code', {
          params: {
              mobile
          }
      })
      console.log('sendMobileMsg',res)
    },
    // 封装短信登录接口
    async mobileLogin(mobile: string, code: string) {
      const res = await request.post<IResponse<Profile>>('/login/code', {
          mobile,
          code
      })
      this.profile = res.data.result
    },
    // 退出登录
    logout() {
      this.profile = {} as Profile
      removeProfile()
      // 清空购物车
      const {cart} = useStore()
      cart.clearCart()
    },
    // source: 1 为 pc，2 为 webapp，3 为微信小程序, 4 为 Android, 5 为 ios, 6 为 qq, 7 为微信 -> 使用qq登录
    async qqLogin(openId: string) {
      const res = await request.post<IResponse<Profile>>('/login/social', {
          unionId: openId,
          source: 6
      })
      // 1. 保存用户信息到 state 中
      this.profile = res.data.result
      setProfile(res.data.result)
    },
    // 绑定 QQ 的短信验证码
    async sendQQBindMsg(mobile: string) {
      await request.get('/login/social/code', {
          params: {
              mobile
          }
      })
    },
    // 根据 openid 和手机号（注册过的）及验证码进行绑定
    async qqBindLogin(openId: string, mobile: string, code: string) {
      const res = await request.post<IResponse<Profile>>('/login/social/bind', {
        mobile,
        code,
        unionId: openId,
      })
      this.profile = res.data.result
      setProfile(res.data.result)
    },
    // 无账号发送验证码
    async sendQQPathMsg(mobile: string) {
      await request.get('/register/code', {
        params: {
          mobile,
        },
      })
    },
    // 无账号，注册并绑定
    async qqPatchLogin(data: any) {
      const res = await request.post<IResponse<Profile>>(`/login/social/${data.openId}/complement`, data)
      // 1. 保存用户信息到 state 中
      this.profile = res.data.result
      setProfile(res.data.result)
    },
  },
})